package cn.com.paycn.ken.utils;

import it.sauronsoftware.base64.Base64;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt
{
  public static void main(String[] args)
  {
    String md5_1 = md5("123456");
    String md5_2 = md5("Bob Chen");

    String sha_1 = sha("123456");
    String sha_2 = sha("Bob Chen");
  }

  public static String e(String inputText) {
    return md5(inputText);
  }

  public static String d(String inputText) {
    return base64Decode(inputText, new String[] { "UTF-8" });
  }

  public static String base64Encode(String inputText, String[] charset)
  {
    if (charset.length == 1) {
      return Base64.encode(inputText, charset[0]);
    }
    return Base64.encode(inputText);
  }

  public static String base64Decode(String inputText, String[] charset)
  {
    if (charset.length == 1) {
      return Base64.decode(inputText, charset[0]);
    }
    return Base64.decode(inputText);
  }

  public static String md5AndSha(String inputText)
  {
    return sha(md5(inputText));
  }

  public static String md5(String inputText)
  {
    return encrypt(inputText, "md5");
  }

  public static String sha(String inputText)
  {
    return encrypt(inputText, "sha-1");
  }

  private static String encrypt(String inputText, String algorithmName)
  {
    if ((inputText == null) || ("".equals(inputText.trim()))) {
      throw new IllegalArgumentException("请输入要加密的内容");
    }
    if ((algorithmName == null) || ("".equals(algorithmName.trim()))) {
      algorithmName = "md5";
    }
    String encryptText = null;
    try {
      MessageDigest m = MessageDigest.getInstance(algorithmName);
      m.update(inputText.getBytes("UTF8"));
      byte[] s = m.digest();

      return hex(s);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return encryptText;
  }

  private static String hex(byte[] arr)
  {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < arr.length; i++) {
      sb.append(Integer.toHexString(arr[i] & 0xFF | 0x100).substring(1, 3));
    }
    return sb.toString();
  }
}